﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iot.Protocol.Modbus
{
    public static class ModbusEndianConverter
    {
        // 原始顺序 (ABCD) - 不转换
        public static ushort[] ConvertABCD(ushort[] values)
        {
            return values;
        }

        // 字节交换 (BADC) - 每个16位字内字节交换
        public static ushort[] ConvertBADC(ushort[] values)
        {
            return values.Select(v => (ushort)((v >> 8) | (v << 8))).ToArray();
        }

        // 字交换 (CDAB) - 保持字节顺序但交换字顺序
        public static ushort[] ConvertCDAB(ushort[] values)
        {
            if (values.Length % 2 != 0)
                throw new ArgumentException("Input array length must be even for CDAB conversion");

            ushort[] result = new ushort[values.Length];
            for (int i = 0; i < values.Length; i += 2)
            {
                result[i] = values[i + 1];
                result[i + 1] = values[i];
            }
            return result;
        }

        // 字节和字都交换 (DCBA) - 字节和字都交换
        public static ushort[] ConvertDCBA(ushort[] values)
        {
            if (values.Length % 2 != 0)
                throw new ArgumentException("Input array length must be even for DCBA conversion");

            ushort[] result = new ushort[values.Length];
            for (int i = 0; i < values.Length; i += 2)
            {
                // 交换字节顺序
                ushort word1 = (ushort)((values[i] >> 8) | (values[i] << 8));
                ushort word2 = (ushort)((values[i + 1] >> 8) | (values[i + 1] << 8));

                // 交换字顺序
                result[i] = word2;
                result[i + 1] = word1;
            }
            return result;
        }
    }
}
